<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="KEY" prop="configKey">
        <el-input style="width:200px" v-model="form.configKey" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="configName">
        <el-input  style="width:200px" v-model="form.configName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
         style="width:200px"
          type="textarea"
          v-model="form.remark"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="导入关系" prop="configType">
        <el-radio-group v-model="form.configType">
          <el-radio-button label="1">一对一</el-radio-button>
          <el-radio-button label="2">一对多</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <div style="color: red; margin: 40px">
        请选择以下信息后再设置其他栏目，改动将清空其他栏目填写的信息，请谨慎操作
      </div>
      <el-form-item label="导入表" prop="formKey">
        <el-select
          v-model="form.formKey"
          @change="
            (e) => {
              getColumns(e, true);
            }
          "
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in formList"
            :key="index"
            :label="item.name"
            :value="item.formKey"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联表（可选）" prop="conFormKey">
        <el-select
          clearable
          v-model="form.relevanceFormKey"
          @change="getColumns"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in formList"
            v-show="item.formKey != form.formKey"
            :key="index"
            :label="item.name"
            :value="item.formKey"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- &&form.relevanceFormKey -->
      <el-form-item label="唯一标识、 关联关系" prop="relevanceConditions" v-if="form.formKey">
		  <div style="width:800px;">
		  	<preview ref="previewRef" v-if="relevanceSchema.body[0].fields.length" :previewConfig="{schema:relevanceSchema}" />
		  </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup name='Basic'>
const emits = defineEmits(['setFormKeyAndColumns','setJson']);
import { details } from "@/api/tool/formManage";
import preview from "@/views/tool/view/index.vue";

const { proxy } = getCurrentInstance();
const props = defineProps({
  formList: {
    type: Array,
    defulat: () => [],
  },
  basic: {
    type: Object,
    defulat: () => null,
  },
  formKey: {
        type: String,
        defulat: ''
      },
});

const form = $ref({
  configKey: undefined,
  configName: undefined,
  remark: undefined,
  configType: "1",
  formKey: undefined,
  relevanceFormKey: undefined,
  relevanceConditions: undefined,
}),
   relevanceSchema =$ref({
    "type": "form",
          "name": 'conditionsForm',
          "data": {},
          "debug": false,
          "wrapWithPanel": false,
          "body": [{
            "type": "condition-builder",
            "name": "conditions",
            "builderMode": "simple",
            "showANDOR": true,
            "fields": [],
          }]
   }),
   formKeyColumns=$ref({}),
        primaryKeyFieldObj=$ref({}),//表的主键
        rules=$ref({
          configKey: [{
            required: true,
            message: '请输入KEY',
            trigger: 'blur'
          }],
          configName: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          formKey: [{
            required: true,
            message: '请选择导入表',
            trigger: 'change'
          }],
          relevanceConditions: [
            // {  required: true,validator: valid}
          ],
        });

    function get(){
        setTimeout(()=>{
        if (props.basic) {
          form ={...props.basic}

          getColumns(form.formKey,true)
          if(props.basic.relevanceFormKey){
            form.relevanceFormKey = props.basic.relevanceFormKey
            relevanceSchema.data.conditions=form.relevanceConditions||{}
            setTimeout(()=>{
              getColumns(form.relevanceFormKey)
            },200)
          }
        }
      },300)  
    }

   //获取表单字段
    function getColumns(formKey,isMain) {
        if(isMain){
          //导入表变化
          form.relevanceFormKey=undefined
        }
        if (formKeyColumns[formKey]) {
          setFormKeyAndColumns()

          relevanceChange(formKey)
        } else {
          details(formKey).then(res => {
            if (res.code == 200) {
              formKeyColumns[formKey] = []
              if(res.data){
                primaryKeyFieldObj[formKey]=res.data.primaryKeyField//表的主键
                formKeyColumns[formKey] = res.data.columns.map(item=>{
                  item.columnName=formKey+'__'+item.columnName
                  return item
                })
              }
              setFormKeyAndColumns()
              relevanceChange(formKey)
            }
          })
        }
      }

    function setFormKeyAndColumns(){
      emits('setFormKeyAndColumns', {
          formKey:form.formKey,
          relevanceFormKey:form.relevanceFormKey,
          formColumns: formKeyColumns,
          primaryKeyFieldObj: primaryKeyFieldObj,
        })
    }
      //关联表变化
    function relevanceChange(formKey){
        relevanceSchema.body[0].fields=[]
        if(form.formKey&&formKeyColumns[form.formKey]){
          nextTick(()=>{
            //关联关系
            let fields=[]
            formKeyColumns[form.formKey].forEach(item => {
              let columnJson = JSON.parse(item.columnJson),
                field = {
                  "label": item.columnTitle,
                  "name": item.columnName,
                  "type": 'select',
                   searchable:true,
                   operators :['select_equals']
                };
                if(form.relevanceFormKey&&formKeyColumns[form.relevanceFormKey]){
                  field.options=formKeyColumns[form.relevanceFormKey].map(ite=>{
                      ite.value=ite.columnName,
                      ite.label=ite.columnTitle
                      return ite
                  })
                }else{
                  field.options=[]
                }
                fields.push(field)
            })
            relevanceSchema.body[0].fields=fields
          })
        }
      }

     function submit() {
        if(proxy.$refs['previewRef']){
          proxy.$refs['previewRef'].getValues('conditionsForm').then(res => {
            form.relevanceConditions=res.conditions||undefined
          })
        }
        setTimeout(()=>{
            proxy.$refs['formRef'].validate((valid) => {
            if (valid) {
              emits('setJson', {
                tabType: 'basic',
                formData: {...form}
              })
            }
          });
        },1000)
      }

      get()

    defineExpose({
        submit,
    });
</script>
<style lang="scss" scoped>
</style>
